//
//  SelectLocationViewController.m
//  CKApp
//
//  Created by CC on 2020/9/14.
//  Copyright © 2020 This Moment. All rights reserved.
//

#import "SelectLocationViewController.h"
#import "LcFoundation.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "AuthorizationManager.h"
#import <YYModel/YYModel.h>

@interface SelectLocationViewController () <MAMapViewDelegate, AMapSearchDelegate>
@property(nonatomic, weak) IBOutlet UIView* mapContainer;
@property(nonatomic, weak) IBOutlet UIView* bottomContainer;
@property(nonatomic, weak) IBOutlet UILabel* poiNameLabel;
@property(nonatomic, weak) IBOutlet UILabel* addressLabel;
@property(nonatomic, weak) IBOutlet UIButton* confirmButton;
@property(nonatomic, strong) MAMapView* mapView;
@property(nonatomic, strong) AMapSearchAPI* search;
@property(nonatomic, strong) LocationMeta* meta;

@property(nonatomic, strong) OnClickedHandler selectHandler;
@end

@implementation SelectLocationViewController

- (instancetype)initWithLocationMeta:(LocationMeta*)meta
                       selectHandler:(OnClickedHandler)selectHandler {
  self = [super init];
  if (self) {
    if (meta == nil) {
      self.meta = [[LocationMeta alloc] init];
    } else {
      self.meta = [meta yy_modelCopy];
    }
    self.selectHandler = selectHandler;
  }
  return self;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setTransparentNavigationBar];
  [self.bottomContainer.layer setCornerRadius:18.0];
  [self.bottomContainer setBackgroundColor:LC_COLOR_BACKGROUND_BLUE_BLACK];
  [self.addressLabel setLcFont:[LcFont wr14]];
  [self.poiNameLabel setLcFont:[LcFont wb17]];

  [self.confirmButton setRedStyle];
  [self.confirmButton.layer setCornerRadius:20.0];
  [self.confirmButton setTitle:@"确定"];

  self.search = [[AMapSearchAPI alloc] init];
  self.search.delegate = self;
  LcWeakSelf;
  [[AuthorizationManager sharedInstance] useSystemLocation:^(BOOL accessGranted, BOOL isSkipped) {
    LcStrongSelf;
    if (accessGranted) {
      [self initMapView];
    } else {
      [UIAlertController showAlert:@"无法获取当前位置，不能使用定位功能"
                               msg:nil
                          tapBlock:^(UIAlertAction* action, NSInteger buttonIndex) {
                            [self navigationBack];
                          }];
    }
  }];
}

- (void)initMapView {
  if (self.mapView == nil) {
    self.mapView = [[MAMapView alloc] initWithFrame:self.mapContainer.bounds];
    [self.mapView setDelegate:self];
    self.mapView.showsScale = NO;
    self.mapView.showsUserLocation = YES;
    self.mapView.showsCompass = NO;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    if ([self.meta locationValid]) {
      self.mapView.centerCoordinate =
          CLLocationCoordinate2DMake(self.meta.latitude, self.meta.longitude);
    }
    [self.mapContainer addSubview:self.mapView];
    [self.mapContainer sendSubviewToBack:self.mapView];
  }
  [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self.mapView setZoomLevel:16.5 animated:YES];
  }
                                                delay:0.5];
}

#pragma mark - ButtonAction
- (IBAction)clickedButton:(id)sender {
  if (self.selectHandler != nil) {
    self.selectHandler(self.meta);
  }
  [super navigationBack];
}

#pragma mark - MAMapViewDelegate
- (void)mapView:(MAMapView*)mapView regionDidChangeAnimated:(BOOL)animated {
  CLLocationCoordinate2D centerCoordinate = mapView.region.center;
  AMapReGeocodeSearchRequest* regeo = [[AMapReGeocodeSearchRequest alloc] init];
  regeo.location = [AMapGeoPoint locationWithLatitude:centerCoordinate.latitude
                                            longitude:centerCoordinate.longitude];
  regeo.requireExtension = YES;
  [self.search AMapReGoecodeSearch:regeo];
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError*)error {
}

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest*)request
                     response:(AMapReGeocodeSearchResponse*)response {
  AMapPOI* poi = response.regeocode.pois.firstObject;
  [self.poiNameLabel setText:poi.name];
  [self.addressLabel setText:response.regeocode.formattedAddress];
  self.meta.address = response.regeocode.formattedAddress;
  self.meta.poiName = poi.name;
  self.meta.cityName = poi.city;
  self.meta.latitude = poi.location.latitude;
  self.meta.longitude = poi.location.longitude;
}

@end
